package cn.iocoder.yudao.module.brokerage.merchant.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.ShopSimpleVO;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.business.basic.service.impl.MerchantScopeService;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.util.TransactionUtils;
import cn.iocoder.yudao.module.api.member.agency.AgencyUserApi;
import cn.iocoder.yudao.module.api.member.agency.vo.AgencyUserVO;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.brokerage.merchant.convert.BrokerageMerchantConvert;
import cn.iocoder.yudao.module.brokerage.merchant.dao.BrokerageMerchantMapper;
import cn.iocoder.yudao.module.brokerage.merchant.mq.BrokerageAgencyProducer;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.po.AgencyMerchantDO;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.vo.AdminBrokerageMerchantQueryDTO;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.vo.AdminBrokerageMerchantVO;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * 推广商家 Service 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Service
@Validated
public class AdminBrokerageMerchantServiceImpl extends MerchantScopeService<AgencyMerchantDO, AdminBrokerageMerchantVO, AdminBrokerageMerchantQueryDTO> implements AdminBrokerageMerchantService {
    @Resource
    private BrokerageMerchantMapper brokerageMerchantMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AppBrokerageMerchantService appBrokerageMerchantService;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ShopInfoApi shopInfoApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AgencyUserApi agencyUserApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private MemberUserApi memberUserApi;

    @Resource
    private BrokerageAgencyProducer brokerageAgencyProducer;

    @Override
    protected BrokerageMerchantMapper getInjectedMapper() {
        return brokerageMerchantMapper;
    }

    @Nonnull
    @Override
    protected CoreQueryWrapper<AgencyMerchantDO> buildQueryWrapper(AdminBrokerageMerchantQueryDTO param) {
        CoreQueryWrapper<AgencyMerchantDO> wrapper = super.buildQueryWrapper(param);
        if (param == null) {
            return wrapper;
        }
        Set<Long> userIds = memberUserApi.getUserIdsByMobileAndNick(param.getMobile(), param.getNickname());
        wrapper.in(CollUtil.isNotEmpty(userIds), "agency_user_id", userIds);
        wrapper.eqIfPresent("agency_user_id", param.getAgencyUserId());
        wrapper.eqIfPresent("shop_id", param.getShopId());
        wrapper.orderByDesc("id");
        return wrapper;
    }

    @Override
    public AdminBrokerageMerchantVO convertToViewObject(AgencyMerchantDO entity) {
        return BrokerageMerchantConvert.INSTANCE.convert2(entity);
    }

    @Override
    public List<AdminBrokerageMerchantVO> convertToViewObject(@Nonnull List<AgencyMerchantDO> entities) {
        List<AdminBrokerageMerchantVO> voList = super.convertToViewObject(entities);
        Set<Long> agencyUserIds = convertSet(voList, AdminBrokerageMerchantVO::getAgencyUserId);
        Map<Long, UserSimpleVO> users = memberUserApi.getUserSimpleMap(agencyUserIds);
        for (AdminBrokerageMerchantVO vo : voList) {
            UserSimpleVO userSimpleVO = users.getOrDefault(vo.getAgencyUserId(), UserSimpleVO.ANONYMOUS);
            vo.setAgencyUser(userSimpleVO);
        }
        return voList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean bindRelation(Long shopId, Long agencyUserId) {
        if (shopId == null || shopId <= 0) {
            log.warn("[bindRelation] 未传递店铺编号，不绑定与招商人员的关系");
            return false;
        }
        if (agencyUserId == null || agencyUserId <= 0) {
            log.warn("[bindRelation] 未传递招商人员用户编号，不绑定与店铺({})的关系", shopId);
            return false;
        }
        AgencyMerchantDO entity = appBrokerageMerchantService.getOrCreate(shopId);
        Assertions.notNull(entity, "商家与招商人员关系绑定失败");
        // 幂等性校验，防止重复绑定
        if (entity.getAgencyUserId() != null && entity.getAgencyUserId() > 0) {
            log.warn("[bindRelation] 推广商家({})已被招商人员用户({})绑定关系", shopId, entity.getAgencyUserId());
            return false;
        }
        AgencyUserVO agencyUser = agencyUserApi.getAgencyUserByUserId(agencyUserId);
        Assertions.notNull(agencyUser, "招商人员信息不存在：" + agencyUserId);
        entity.setAgencyUserId(agencyUserId);
        getInjectedMapper().updateById(entity);
        TransactionUtils.afterCommit(() -> {
            brokerageAgencyProducer.sendAgencyBindMessage(shopId, agencyUserId);
            return null;
        });
        return true;
    }

    @Nonnull
    @Override
    protected Map<Long, ShopSimpleVO> getShopSimpleMap(Collection<Long> shopIds) {
        return shopInfoApi.getShopSimpleMap(shopIds);
    }

}